package cn.aifeix.pet.service.impl;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.basic.constant.BaseConstant;
import cn.aifeix.basic.domain.Point;
import cn.aifeix.basic.service.impl.BaseServiceImpl;
import cn.aifeix.basic.util.*;
import cn.aifeix.order.domain.OrderPetAcquisition;
import cn.aifeix.order.domain.RejectionLog;
import cn.aifeix.order.service.IOrderPetAcquisitionService;
import cn.aifeix.order.service.IRejectionLogService;
import cn.aifeix.org.domain.Employee;
import cn.aifeix.org.domain.Shop;
import cn.aifeix.org.service.EmployeeService;
import cn.aifeix.org.service.IShopService;
import cn.aifeix.pet.domain.SearchMasterMsg;
import cn.aifeix.pet.domain.SearchMasterMsgAuditLog;
import cn.aifeix.pet.dto.AcceptOrderFormDto;
import cn.aifeix.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.aifeix.pet.mapper.SearchMasterMsgMapper;
import cn.aifeix.pet.query.SearchMasterMsgQuery;
import cn.aifeix.pet.service.ISearchMasterMsgService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aifeix
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private IShopService shopService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Autowired
    private IRejectionLogService rejectionLogService;

    /**
     * 寻主发布
     * @param searchMasterMsg
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 保存到数据库
        searchMasterMsgMapper.add(searchMasterMsg);
        // 参数非空校验
        ParmCheck(searchMasterMsg);
        // 百度ai校验
        baiduAiCheck(searchMasterMsg);
        // 成功则分配50公里内最近店铺,设置shopId
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shops = shopService.findAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        if (shop != null){
            searchMasterMsg.setShopId(shop.getId());
        }
        // 修改状态为通过
        searchMasterMsg.setState(1);
        // 调用数据库修改
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> selectMasterMsgByParam(SearchMasterMsgQuery searchMasterMsg) {
        // 查询条数
        Integer totals = searchMasterMsgMapper.selectMasterMsgByParamQueryByCount(searchMasterMsg);
        if (null == totals || 0 == totals){
            return new PageList<>(0,new ArrayList<>());
        }
        // 查询数据
        List<SearchMasterMsg> employees = searchMasterMsgMapper.selectMasterMsgByParam(searchMasterMsg);
        //方到返回里面
        return new PageList<>(totals,employees);
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void accept(AcceptOrderFormDto dto) {
        // 根据消息id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(dto.getMsgId());
        // 为null抛异常
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空");
        }
        // 解决线程安全问题
        synchronized (searchMasterMsg.getId()){
            Employee employee = employeeService.findById(dto.getHandler());
            if (null == employee){
                throw new BussinessException("不存在该员工");
            }
            if (searchMasterMsg.getState() == 1 && searchMasterMsg.getShopId() == employee.getShopId()){
                // 修改寻主消息状态为2
                searchMasterMsg.setState(2);
                searchMasterMsgMapper.update(searchMasterMsg);
                // 生成收购单
                initOrderPetAcquisition(dto, employee, searchMasterMsg);
            }
        }
    }

    /**
     * 订单初始化
     * @param dto
     * @param employee
     * @param searchMasterMsg
     */
    private void initOrderPetAcquisition(AcceptOrderFormDto dto, Employee employee, SearchMasterMsg searchMasterMsg) {
        OrderPetAcquisition orderPetAcquisition = OrderPetAcquisition.builder()
                .orderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()))
                .digest(dto.getNote())
                .lastcomfirmtime(new Date(System.currentTimeMillis() + BaseConstant.TimeCons.LAST_CONFIRM_TIME))
                .state(0)
                // 用户发布的金额，不是最终金额
                .price(new BigDecimal(searchMasterMsg.getPrice()))
                .userId(searchMasterMsg.getUserId())
                .shopId(employee.getShopId())
                .address(searchMasterMsg.getAddress())
                .empId(employee.getId())
                .searchMasterMsgId(searchMasterMsg.getId())
                .build();
//        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
//        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
//        orderPetAcquisition.setDigest(dto.getNote());
//        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + BaseConstant.TimeCons.LAST_CONFIRM_TIME));
//        orderPetAcquisition.setState(0);
//        // 用户发布的金额，不是最终金额
//        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
//        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
//        orderPetAcquisition.setShopId(employee.getShopId());
//        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
//        orderPetAcquisition.setEmpId(employee.getId());
//        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        // 添加到回购单表中
        orderPetAcquisitionService.add(orderPetAcquisition);
        sendMessage(orderPetAcquisition.getId());
    }

    /**
     * 发送消息
     * @param id
     * @throws Exception
     */
    public void sendMessage(Long id){
        try {
            // 1.创建生产者对象，指定生产者组名
            DefaultMQProducer producer = new DefaultMQProducer("pet_group_w");
            // 2.连接mq
            producer.setNamesrvAddr("localhost:9876");
            // 3.启动生产者
            producer.start();
            // 4.发送消息
            // 4.1.创建消息体
            // topic：消息主题 tags：此主题下的二级分类 body：消息的字节
            Message message = new Message("order-topic", "pet-delay-tag", id.toString().getBytes());
            // 延迟消息
            message.setDelayTimeLevel(4);
            // 4.2.发送消息
            SendResult sendResult = producer.send(message);
            // 4.3.打印消息发送结果
            System.out.println(sendResult);
            System.out.println(sendResult.getSendStatus());
            // 5.关闭生产者
            producer.shutdown();
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拒单
     * @param msgId
     * @param employee
     */
    @Override
    public void reject(Long msgId, Employee employee) {
        // 根据消息id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        // 为null抛异常
        if (null == searchMasterMsg){
            throw new BussinessException("寻主消息为空");
        }
        // 清空shopId
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 保存到拒单日志表
        RejectionLog rejectionLog = RejectionLog.builder()
                .empId(employee.getId())
                .msgId(searchMasterMsg.getId())
                .rejectionTime(new Date())
                .build();
        rejectionLogService.add(rejectionLog);

    }

    /**
     * 百度AI审核
     * @param searchMasterMsg
     */
    private void baiduAiCheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder sbr = new StringBuilder();
        sbr.append(searchMasterMsg.getName())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getNote());
        if (!BaiduAuditUtils.TextCensor(sbr.toString())){
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setAuditId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("信息违规，审核失败，请在个人中心中修改");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            throw new BussinessException("信息违规，审核失败，请在个人中心中修改");
        }
    }

    /**
     * 参数非空校验
     * @param searchMasterMsg
     */
    private void ParmCheck(SearchMasterMsg searchMasterMsg) {
        if (StringUtils.isEmpty(searchMasterMsg.getName()) || StringUtils.isEmpty(searchMasterMsg.getAddress())){
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setAuditId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("参数为空，审核失败，请在个人中心中修改");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            throw new BussinessException("参数为空，审核失败，请在个人中心中修改");
        }
    }
}
